package net.example.activity.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.TextView;

import com.oraycn.esframework.core.ClientType;

import net.example.activity.ChatActivity;
import net.example.activity.SearchFriendActivity;
import net.example.activity.adapter.FriendAdapter;
import net.example.manager.ClientGlobalCache;
import net.example.model.common.MessageFont;
import net.example.model.common.RichChatMessage;
import net.example.model.event.ChatEvent;
import net.example.model.FriendCatalogContainer;
import net.example.manager.GGApplication;
import net.example.model.event.ClickToChatEvent;
import net.example.model.event.FriendAddedNotifyEvent;
import net.example.model.event.FriendCatalogChangedEvent;
import net.example.model.event.FriendCommentNameChangedEvent;
import net.example.model.event.FriendDeletedNotifyEvent;
import net.example.model.event.UserEvent;
import net.example.model.GGUser;
import net.example.model.event.UserHeadImageChangedEvent;
import net.example.model.event.UserInfoChangedEvent;
import net.example.ggtalk.R;
import net.example.utils.ConfigUtils;
import net.example.utils.IntentUtils;
import net.example.utils.PinyinComparator;
import net.example.activity.view.PinnedHeaderExpandableListView;
import net.example.activity.view.StickyLayout;
import net.example.utils.ToastUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

public class FriendFragment extends Fragment implements
        ExpandableListView.OnChildClickListener,
        ExpandableListView.OnGroupClickListener,
        PinnedHeaderExpandableListView.OnHeaderUpdateListener, StickyLayout.OnGiveUpTouchEventListener {
    public static FriendFragment mFragment;
    private View mView;
    private ArrayList<FriendCatalogContainer> friendCatalogContainers = new ArrayList<>();
    private PinnedHeaderExpandableListView expandableListView;
    private StickyLayout stickyLayout;

    private FriendAdapter adapter;
    GGUser currentItem = null;

    public static Fragment getInstance() {
        mFragment = new FriendFragment();
        return mFragment;
    }

    public void onEventMainThread(UserEvent event) {

        for (FriendCatalogContainer friendCatalogContainer : friendCatalogContainers
        ) {
            for (GGUser user : friendCatalogContainer.getGroupChild()) {
                if (user.getUserID().equals(event.userID)) {
                    user.setUserStatus(event.status);
                    user.statusChanged = true;
                    break;
                }
            }
        }
        this.refreshFriendListRank();
    }

    public void onEventMainThread(UserInfoChangedEvent event)
    {
        this.refreshUserInfo(event.UserID);
    }

    public void onEventMainThread(UserHeadImageChangedEvent event){
        adapter.notifyDataSetChanged();
    }

    public void onEventMainThread(ChatEvent event) {
        if(event.groupID.equals(GGApplication.getInstance().TALKINGUSER))
        {
            return;
        }
        if(event.isEcho)
        {
            return;
        }
        if(event.clientType == ClientType.ANDROID && event.groupID.equals(GGApplication.getInstance().getCurrentUser().getUserID()))
        {
            return;
        }
        for (FriendCatalogContainer friendCatalogContainer : friendCatalogContainers
        ) {
            for (GGUser user : friendCatalogContainer.getGroupChild()) {
                if (user.getUserID().equals(event.groupID)) {
                    user.isNewMsg = true;
                    break;
                }
            }
        }
        this.refreshFriendListRank();
    }

    public void onEventMainThread(ClickToChatEvent event)
    {
        for (FriendCatalogContainer friendCatalogContainer : friendCatalogContainers
        ) {
            for (GGUser user : friendCatalogContainer.getGroupChild()) {
                if (user.getUserID().equals(event.friendID)) {
                    user.isNewMsg = false;
                    break;
                }
            }
        }
        this.refreshFriendListRank();

    }

    public void onEventMainThread(FriendAddedNotifyEvent event) {
        FriendCatalogContainer defaultFriendCatalogContainer = new FriendCatalogContainer();
        GGUser GGUser = event.getGGUser();
        ClientGlobalCache.getInstance().reLoadCurrentUserFromServer();
        for (FriendCatalogContainer friendCatalogContainer : friendCatalogContainers
        ) {
            //若列表中已经有了该用户 直接返回
            if(containsUserID(friendCatalogContainer.getGroupChild(), GGUser.getUserID()))
            {
                return;
            }
            if (friendCatalogContainer.getgroupName().equals(event.CatalogName)) {
                defaultFriendCatalogContainer = friendCatalogContainer;
                break;
            }
        }
        defaultFriendCatalogContainer.add(0, GGUser);
        GGUser.isNewMsg = !event.IsActiveSend;
        this.refreshFriendListRank();
        if (event.IsActiveSend) {
            return;
        }
        GGApplication.getInstance().ringForMessage();
        RichChatMessage richChatMessage = new RichChatMessage();
        String msg = "我添加您为好友了";
        richChatMessage.setText(msg);
        richChatMessage.setFont(new MessageFont());
        String sendID = event.IsActiveSend ? ClientGlobalCache.getInstance().getCurrentUser().getUserID() : event.getGGUser().getUserID();
        ChatEvent chatEvent = new ChatEvent(sendID, ClientType.ServerSide, sendID, richChatMessage, false);
        EventBus.getDefault().post(chatEvent);
    }

    public void onEventMainThread(FriendDeletedNotifyEvent event){
        ClientGlobalCache.getInstance().reLoadCurrentUserFromServer();
        GGUser GGUser =event.getGGUser();
        for (FriendCatalogContainer friendCatalogContainer : friendCatalogContainers
        ) {
            for (GGUser user : friendCatalogContainer.getGroupChild()) {
                if (user.getUserID().equals(GGUser.getUserID())) {
                    friendCatalogContainer.remove(user);
                    ClientGlobalCache.getInstance().DeleteChatMessageRecordInLocalDB(user.getUserID(),false);
                     adapter.notifyDataSetChanged();
                    return;
                }
            }
        }
    }
    
    public void onEventMainThread(FriendCatalogChangedEvent event)
    {
        ClientGlobalCache.getInstance().reLoadCurrentUserFromServer();
        this.initFriendCatalogContainersData();
        adapter.notifyDataSetChanged();
    }

    public void onEventMainThread(FriendCommentNameChangedEvent event)
    {
        adapter.notifyDataSetChanged();
    }



    //界面刷新已改变的用户资料
    private void refreshUserInfo(String userID)
    {
        for (FriendCatalogContainer friendCatalogContainer : friendCatalogContainers
        ) {
            for (GGUser user : friendCatalogContainer.getGroupChild()) {
                if (user.getUserID().equals(userID)) {
                    user=ClientGlobalCache.getInstance().getUser(userID);
                    adapter.notifyDataSetChanged();
                    return;
                }
            }
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        try {
            mView = inflater.inflate(R.layout.friend_expandable, container, false);
            expandableListView = (PinnedHeaderExpandableListView) mView.findViewById(R.id.expandablelist);
            stickyLayout = (StickyLayout) mView.findViewById(R.id.sticky_layout);
            initFriendCatalogContainersData();
            adapter = new FriendAdapter(getActivity().getApplicationContext(), friendCatalogContainers);
            expandableListView.setAdapter(adapter);
            if (friendCatalogContainers.size() > 0) {
                expandableListView.setOnHeaderUpdateListener(this);
                expandableListView.setOnChildClickListener(this);
                expandableListView.setOnGroupClickListener(this);
                stickyLayout.setOnGiveUpTouchEventListener(this);
            }
            expandableListView.expandGroup(0);
            if (!EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().register(this);
            }
            TextView tv_title= (TextView) mView.findViewById(R.id.message_title);
            tv_title.setText(R.string.myfriends);
            ImageButton btn_moveToSearchFriend=(ImageButton) mView.findViewById(R.id.plus_btn);
            btn_moveToSearchFriend.setVisibility(View.VISIBLE);
            btn_moveToSearchFriend.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    IntentUtils.startActivity(getActivity(), SearchFriendActivity.class);
                }
            });
            return mView;
        }
        catch (Exception ex)
        {
            ToastUtils.showLongTemp(getActivity(),ex.getMessage());
            return null;
        }
    }



    private void initFriendCatalogContainersData() {
        GGUser currentUser = ClientGlobalCache.getInstance().getCurrentUser();
        HashMap<String,ArrayList<String>> map = currentUser.getFriendMap();
        friendCatalogContainers.clear();
        for (Map.Entry<String,ArrayList<String>> pair : map.entrySet()) {
            FriendCatalogContainer container = new FriendCatalogContainer();
            List<GGUser> list = new ArrayList<>();
            container.setgroupName(pair.getKey());
            for (String id :  pair.getValue()) {
                GGUser fUser = ClientGlobalCache.getInstance().getUser(id);
                if (fUser != null&& !fUser.getUserID().equals(currentUser.getUserID())&&!containsUserID(list,fUser.getUserID())) {
                    list.add(fUser);
                }
            }
            container.setGroupChild(list);
            friendCatalogContainers.add(container);
        }
        this.refreshFriendCatalogRank();
        FriendCatalogContainer firstContainer=friendCatalogContainers.get(0);
        firstContainer.add(0,currentUser);

    }

    //检查集合中是否包含该用户
    private boolean containsUserID(List<GGUser> list, String userID)
    {
        if(list==null){return false;}
        for (GGUser user:list) {
            if(user.getUserID().equals(userID)){return true;}
        }
        return false;
    }
    
    //刷新好友分组排行
    private void refreshFriendCatalogRank()
    {
        Collections.sort(friendCatalogContainers, new Comparator<FriendCatalogContainer>() {
            @Override
            public int compare(FriendCatalogContainer x, FriendCatalogContainer y) {
                if(x.getgroupName().equals(getResources().getString(R.string.friend_catalog_name)))
                {
                    return -1;
                }
                if(y.getgroupName().equals(getResources().getString(R.string.friend_catalog_name)))
                {
                    return 1;
                }
                if(x.getgroupName().equals(getResources().getString(R.string.blacklist)))
                {
                    return 1;
                }
                if(y.getgroupName().equals(getResources().getString(R.string.blacklist)))
                {
                    return -1;
                }
                return PinyinComparator.compare(x.getgroupName(),y.getgroupName());
            }
        });
    }

    //刷新好友列表排行 (先根据状态排，在线在最上方。同状态根据是否有新消息排，最后根据名称的字母排)
    private void refreshFriendListRank()
    {
        final String currentUserID=ClientGlobalCache.getInstance().getCurrentUser().getUserID();
        for (FriendCatalogContainer friendCatalogContainer : friendCatalogContainers) {
            Collections.sort(friendCatalogContainer.getGroupChild(), new Comparator<GGUser>() {
                @Override
                public int compare(GGUser x, GGUser y) {
                    if(x.getUserID().equals(currentUserID))
                    {
                        return -1;
                    }
                    if(y.getUserID().equals(currentUserID))
                    {
                        return 1;
                    }
                    int xType = x.getUserStatus().getType();
                    int yType = y.getUserStatus().getType();
                    if (xType == yType) {
                        if (x.isNewMsg && !y.isNewMsg) {
                            return -1;
                        } else if (!x.isNewMsg && y.isNewMsg) {
                            return 1;
                        }
                        return PinyinComparator.compare(x.getName(), y.getName());
                    } else if (xType < yType) {
                        return -1;
                    } else {
                        return 1;
                    }
                }
            });
        }

        adapter.notifyDataSetChanged();
    }

    public void RefreshPage()
    {
        adapter.notifyDataSetChanged();
    }

    @Override
    public View getPinnedHeader() {
        View headerView = getActivity().getLayoutInflater().inflate(R.layout.friend_group_item, null);
        headerView.setLayoutParams(new AbsListView.LayoutParams(
                AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT));
        return headerView;
    }

    @Override
    public void updatePinnedHeader(View headerView, int firstVisibleGroupPos) {
//        FriendCatalogContainer firstVisibleGroup = (FriendCatalogContainer) adapter.getGroup(firstVisibleGroupPos);
//        TextView textView = (TextView) headerView.findViewById(R.id.groupName);
//        textView.setText(firstVisibleGroup.getgroupName());
    }

    @Override
    public boolean giveUpTouchEvent(MotionEvent event) {
        if (expandableListView.getFirstVisiblePosition() == 0) {
            View view = expandableListView.getChildAt(0);
            return view != null && view.getTop() >= 0;
        }
        return false;
    }

    @Override
    public boolean onGroupClick(final ExpandableListView parent, final View v,
                                int groupPosition, final long id) {
        return false;
    }

    @Override
    public boolean onChildClick(ExpandableListView parent, View v,
                                int groupPosition, int childPosition, long id) {
        GGUser user = friendCatalogContainers.get(groupPosition).getChild(childPosition);
        user.isNewMsg = false;
        currentItem = user;
//        if (OrayApplication.getInstance().getCurrentUser().getUserID().equals(user.getUserID())) {
//            ToastUtils.showShort(v.getContext(), "不能点击自己！");
//        } else {
            IntentUtils.startActivityForString_Dubble(getActivity(), ChatActivity.class,
                    ConfigUtils.TalkingType, ConfigUtils.Person_Talking, ConfigUtils.Person_Talking, user.getUserID());
            adapter.notifyDataSetChanged();
//        }
         return true;
    }



    @Override
    public void onResume() {
        super.onResume();
        if (currentItem != null) {
            currentItem.isNewMsg = false;
        }
        this.refreshFriendListRank();
     }

    public void onDestroyView() {
        if (mView != null) {
            ((ViewGroup) mView.getParent()).removeView(mView);
        }
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

}